﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using AtletIS.Shared.Data;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;

namespace AtletIS.Shared.Helpers
{
    public class RegistrationImportHelper
    {
        private static Encoding _encoding = Encoding.GetEncoding(1250); // .GetEncoding("iso-8859-2");

        public static void ImportClubs(string fileName)
        {
            List<string> rows = new List<string>();

            #region Nacitanie

            using (StreamReader readFile = new StreamReader(fileName, _encoding))
            {
                string line;

                while ((line = readFile.ReadLine()) != null)
                {
                    rows.Add(line);
                }
            }

            #endregion

            #region Kontrola

            if (rows == null || rows.Count == 0)
                throw new Exception("Importný súbor jue prázdny!");

            string[] header = rows[0].Split(';');

            if (header == null || header.Length != 9 || header[0] != "Kód" || header[1] != "Názov klubu" || header[2] != "Sídlo")
                throw new Exception("Nesprávny formát importného súboru!");

            #endregion

            aDbDataSet.ClubsDataTable dtClubs = DatabaseHelper.GetClubsAll();

            if (dtClubs == null)
                return;

            // Zneaktivnenie klubov z registracie
            foreach (DataRow drClub in dtClubs)
            {
                if (!string.IsNullOrEmpty(drClub["ExtId"].ToString()))
                    drClub["Active"] = false;
            }

            for (int i = 1; i < rows.Count; i++)
            {
                string[] values = rows[i].Split(';');
                string clubId = values[0];

                DataRow drEdit;

                DataRow[] arr = dtClubs.Select(string.Format("ExtId = '{0}'", clubId));
                if (arr.Count() > 0)
                    drEdit = arr[0];
                else
                {
                    drEdit = dtClubs.NewClubsRow();
                    drEdit["ID"] = clubId;
                    drEdit["ExtId"] = clubId;
                    drEdit["Sync"] = false;

                    dtClubs.Rows.Add(drEdit);
                }

                drEdit["Name"] = values[1].Trim() + " " + values[2].Trim();
                drEdit["City"] = values[2].Trim();
                drEdit["Street"] = values[3].Trim();
                drEdit["Phone"] = values[5].Trim();
                drEdit["Email"] = values[6].Trim();
                drEdit["Web"] = values[7].Trim();
                drEdit["Active"] = true;
                drEdit["Modified"] = DateTime.Now;
            }

            var taClubs = new ClubsTableAdapter();
            taClubs.Update(dtClubs);
        }

        public static void ImportCompetitors(string fileName)
        {
            List<string> rows = new List<string>();

            #region Nacitanie

            using (StreamReader readFile = new StreamReader(fileName, _encoding))
            {
                string line;

                while ((line = readFile.ReadLine()) != null)
                {
                    rows.Add(line);
                }
            }

            #endregion

            #region Kontrola

            if (rows == null || rows.Count == 0)
                throw new Exception("Importný súbor jue prázdny!");

            string[] header = rows[0].Split(';');

            if (header == null || header.Length != 7 || header[0] != "ID" || header[1] != "Priezvisko" || header[2] != "Meno")
                throw new Exception("Nesprávny formát importného súboru!");

            #endregion

            aDbDataSet.ClubsDataTable dtClubs = DatabaseHelper.GetClubsAll();
            aDbDataSet.CompetitorsDataTable dtCompetitors = DatabaseHelper.GetCompetitorsAll();

            if (dtCompetitors == null)
                return;

            // Zneaktivnenie klubov z registracie
            foreach (DataRow drClub in dtCompetitors)
            {
                if (!string.IsNullOrEmpty(drClub["ExtId"].ToString()))
                    drClub["Active"] = false;
            }

            for (int i = 1; i < rows.Count; i++)
            {
                string[] values = rows[i].Split(';');

                bool ok = true;

                if (string.IsNullOrEmpty(values[4]))
                    ok = false;

                if (ok && dtClubs.Select(string.Format("ID = '{0}'", values[4])).Count() == 0)
                    ok = false;

                if (ok)
                {
                    int competitorId = Convert.ToInt32(values[0]);

                    DataRow drEdit;

                    DataRow[] arr = dtCompetitors.Select(string.Format("ExtId = {0}", competitorId));
                    if (arr.Count() > 0)
                        drEdit = arr[0];
                    else
                    {
                        drEdit = dtCompetitors.NewCompetitorsRow();
                        drEdit["ExtId"] = competitorId;
                        drEdit["Sync"] = false;
                        drEdit["WebId"] = 0;

                        dtCompetitors.Rows.Add(drEdit);
                    }

                    try
                    {
                        drEdit["Surname"] = values[1].Trim();
                        drEdit["FirstName"] = values[2].Trim();
                        drEdit["ClubId"] = values[4];
                        drEdit["CountryId"] = "SVK";
                        drEdit["Sex"] = values[6];
                        drEdit["Active"] = true;
                        drEdit["Modified"] = DateTime.Now;
                        drEdit["BirthDate"] = DateTime.ParseExact(values[3], "dd.MM.yyyy", null);
                    }
                    catch // (Exception ex)
                    {
                        drEdit["BirthDate"] = new DateTime(1900, 1, 1);
                        // ExceptionHelper.ShowErrorInfo(ex);
                    }
                }
            }

            var taCompetitors = new CompetitorsTableAdapter();
            taCompetitors.Update(dtCompetitors);
        }



    }
}
